package com.kotlin.android.ktx.ext

import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.annotation.DrawableRes
import androidx.core.content.FileProvider
import java.io.File

/**
 *
 * Created on 2020/6/5.
 *
 * @author o.s
 */

/**
 * 启动app
 */
fun Context.openApp(pkgName: String) {
    packageManager.getLeanbackLaunchIntentForPackage(pkgName)?.run {
        startActivity(this)
    }
}

/**
 * 使用浏览器（外部）访问指定的url页面
 */
fun Context.openBrowser(url: String) {
    Intent(
        Intent.ACTION_VIEW,
        Uri.parse(url)
    ).run {
        startActivity(this)
    }
}

/**
 * app设置页
 */
fun Context.openAppSetting(pkgName: String = packageName) {
    Intent(
        Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
        Uri.fromParts("package", pkgName, null)
    ).run {
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        startActivity(this)
    }
}

/**
 * 安装apk
 * 需要权限 android.permission.REQUEST_INSTALL_PACKAGES
 */
fun Context.installApk(apkFile: File) {
    if (!apkFile.exists()) return
    Intent(
        Intent.ACTION_VIEW
    ).run {
        val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val authority = "$packageName.fileprovider"
            FileProvider.getUriForFile(this@installApk, authority, apkFile)
        } else {
            Uri.fromFile(apkFile)
        }
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        setDataAndType(uri, "application/vnd.android.package-archive")
        startActivity(this)
    }
}

/**
 * 卸载apk
 */
fun Context.uninstallApk(pkgName: String) {
    Intent(
        Intent.ACTION_DELETE
    ).run {
        data = Uri.parse("package:$pkgName")
        startActivity(this)
    }
}

/**
 * 发送邮件
 */
fun Context.sendEmail(email: String, subject: String?, text: String?) {
    Intent(
        Intent.ACTION_SENDTO,
        Uri.parse("mailto:$email")
    ).run {
        subject?.let { putExtra(Intent.EXTRA_SUBJECT, subject) }
        text?.let { putExtra(Intent.EXTRA_TEXT, text) }
        startActivity(this)
    }
}

/**
 * 拷贝文本到粘贴板
 */
fun Context.copyToClipboard(text: String, label: String = "KTX") {
    val clipData = ClipData.newPlainText(label, text)
    clipboardManager?.setPrimaryClip(clipData)
}

fun Context.getDrawable(@DrawableRes id: Int?): Drawable? = id?.let { getDrawable(it) }